package me.shurufa.widget.popupwindow;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsoluteLayout;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;

import net.qiujuer.genius.blur.StackBlur;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import de.greenrobot.event.EventBus;
import me.shurufa.R;
import me.shurufa.net.BaseResponse;
import me.shurufa.net.API;
import me.shurufa.net.RequestServerTask;
import me.shurufa.utils.Constants;
import me.shurufa.utils.FastBlur;
import me.shurufa.utils.Global;
import me.shurufa.utils.HttpUtil;
import me.shurufa.utils.Utils;

/**
 * PopWindow by background blur
 *
 * Notice: use FastBlur or blur(1) is java method test blur time first is 127ms , after is 40~50ms
 * use blur(2) is jni bitmap method test blur time first is 120ms ,after is 20~30ms
 * use blur(3) is jni pixels method test blur time firsr is 104ms ,after is 40+ms
 *
 * recommend to use blur(2)
 * 
 * @FileName: me.khrystal.bluractivitydemo.EditDigestWindow.java
 * @author: kHRYSTAL
 * @email: 723526676@qq.com
 * @date: 2016-01-13 10:37
 */
public class AddCommentWindow extends PopupWindow implements View.OnClickListener{

  Activity mContext;
  private int mWidth;
  private int mHeight;
  private int statusBarHeight;
  private Bitmap mBitmap = null;
  private Bitmap overlay = null;
  private ScaleAnimation mShowAnim;

  TextView sendButton;
  EditText editText;
  View outView;

  private InputMethodManager imm;
  private long bookId;
  private int type;

  public AddCommentWindow(Activity context) {
    mContext = context;
  }


  /**
   * 设置宽高为除去上方状态栏的全屏
   * 实例化后需要手动调用
   */
  public void init(long bookId,int type) {
    this.bookId = bookId;
    this.type = type;
    Rect frame = new Rect();
    mContext.getWindow().getDecorView()
        .getWindowVisibleDisplayFrame(frame);
    statusBarHeight = frame.top;
    DisplayMetrics metrics = new DisplayMetrics();
    mContext.getWindowManager().getDefaultDisplay()
        .getMetrics(metrics);
    mWidth = metrics.widthPixels;
    mHeight = metrics.heightPixels;

    setWidth(mWidth);
    setHeight(mHeight);
    mShowAnim = new ScaleAnimation(0.5f, 1f, 0.5f, 1f, Animation.RELATIVE_TO_SELF, 0.5f,
        Animation.RELATIVE_TO_SELF, 0.5f);
    mShowAnim.setFillAfter(true);
    mShowAnim.setDuration(500);
  }


  /**
   * Java method to blur by FastBlur
   * 
   * @return
   */
  private Bitmap blur() {
    if (null != overlay) {
      return overlay;
    }
    long startMs = System.currentTimeMillis();

    View view = mContext.getWindow().getDecorView();
    view.setDrawingCacheEnabled(true);
    view.buildDrawingCache(true);
    mBitmap = view.getDrawingCache();
    // TODO 去掉通知栏
    int width = mBitmap.getWidth();
    int height = mBitmap.getHeight();
    mBitmap = Bitmap.createBitmap(mBitmap, 0, statusBarHeight, width, height - statusBarHeight);
    height -= statusBarHeight;
    float scaleFactor = 8;// 缩放比例
    float radius = 3;// 模糊程度


    overlay = Bitmap.createBitmap((int) (width / scaleFactor), (int) (height / scaleFactor),
        Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(overlay);
    canvas.scale(1 / scaleFactor, 1 / scaleFactor);
    Paint paint = new Paint();
    paint.setFlags(Paint.FILTER_BITMAP_FLAG);
    canvas.drawBitmap(mBitmap, 0, 0, paint);

    overlay = FastBlur.doBlur(overlay, (int) radius, true);
    Log.i("EditDigestWindow", "blur time is:" + (System.currentTimeMillis() - startMs));
    return overlay;
  }


  private Bitmap blur(int i) {


    long startMs = System.currentTimeMillis();

    // Is scale
    View view = mContext.getWindow().getDecorView();
    view.setDrawingCacheEnabled(true);
    view.buildDrawingCache(true);
    mBitmap = view.getDrawingCache();
    // TODO 去掉通知栏
    int width = mBitmap.getWidth();
    int height = mBitmap.getHeight();
    mBitmap = Bitmap.createBitmap(mBitmap, 0, statusBarHeight, width, height - statusBarHeight);
    height -= statusBarHeight;
    float scaleFactor = 8;// 缩放比例
    float radius = 3;// 模糊程度

    overlay = Bitmap.createBitmap((int) (width / scaleFactor), (int) (height / scaleFactor),
        Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(overlay);
    canvas.scale(1 / scaleFactor, 1 / scaleFactor);
    Paint paint = new Paint();
    paint.setFlags(Paint.FILTER_BITMAP_FLAG);
    canvas.drawBitmap(mBitmap, 0, 0, paint);


    // is blur
    // Java
    if (i == 1)
      overlay = StackBlur.blur(overlay, (int) radius, false);
    // Bitmap JNI Native
    else if (i == 2)
      overlay = StackBlur.blurNatively(overlay, (int) radius, false);
    // Pixels JNI Native
    else if (i == 3)
      overlay = StackBlur.blurNativelyPixels(overlay, (int) radius, false);

    Log.i("EditDigestWindow", "blur time is:" + (System.currentTimeMillis() - startMs));
    return overlay;
  }


  /**
   * display
   * 
   * @param anchor
   * @param bottomMargin
   */
  public void showMoreWindow(View anchor, int bottomMargin) {
    final View rootView =  LayoutInflater
        .from(mContext).inflate(R.layout.pop_add_comment, null);
//    监听返回键
    rootView.setFocusableInTouchMode(true);
    sendButton = (TextView)rootView.findViewById(R.id.popup_send);
    editText = (EditText)rootView.findViewById(R.id.popup_edit);
    outView = rootView.findViewById(R.id.popup_out);
    outView.setOnClickListener(this);
    sendButton.setOnClickListener(this);
    setContentView(rootView);
    setAnimationStyle(android.R.style.Animation_Toast);
    android.widget.RelativeLayout.LayoutParams params =
        new android.widget.RelativeLayout.LayoutParams(AbsoluteLayout.LayoutParams.WRAP_CONTENT,
            AbsoluteLayout.LayoutParams.WRAP_CONTENT);
    params.bottomMargin = bottomMargin;
    params.topMargin = 200;
    params.leftMargin = 18;

    // TODO 设置内部控件 Anim

    // 设置背景高斯模糊
    setBackgroundDrawable(new BitmapDrawable(mContext.getResources(), blur(2)));

    // 外部是否可以点击
    setOutsideTouchable(true);
    setFocusable(true);
    showAtLocation(anchor, Gravity.BOTTOM, 0, statusBarHeight);
    //imm.showSoftInputFromInputMethod(editText.getWindowToken(),0);
    editText.setFocusable(true);
    editText.setFocusableInTouchMode(true);
    editText.requestFocus();
    Timer timer = new Timer();
    timer.schedule(new TimerTask(){
       public void run()
       {
         imm = (InputMethodManager)editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
         imm.showSoftInput(editText, 0);
       }

     }, 500);
  }




  @Override
  public void dismiss() {
    destroy();
    super.dismiss();
  }



  public void destroy() {
    if (null != overlay) {
      overlay.recycle();
      overlay = null;
      System.gc();
    }
    if (null != mBitmap) {
      mBitmap.recycle();
      mBitmap = null;
      System.gc();
    }
  }

  @Override
  public void onClick(View v) {
    switch (v.getId()){
      case R.id.popup_send:
        final String trim = editText.getText().toString().trim();
        if (!TextUtils.isEmpty(trim)&& trim.length()>6) {
          new RequestServerTask<BaseResponse>(BaseResponse.class,mContext,mContext.getString(R.string.commit_pls_wait)){

            @Override
            protected String requestServer() {
              Map<String,Object> params = new HashMap<>();
              params.put("bookId",bookId);
              params.put("content",trim);
              params.put("token", Global.currentUser.token);
              params.put("type",type== Constants.TYPE_COMMENT_BOOK ? "book" : "excerpt");
              return HttpUtil.post(API.COMMENT_ADD,params);
            }

            @Override
            protected void onSuccess(BaseResponse result) {
              if (result.success) {
//                通知外部页面刷新
                EventBus.getDefault().post(new Intent(Constants.ACTION_BOOKINFO_COMMENT_REFRESH));
                AddCommentWindow.this.dismiss();
              }
            }
          }.start();
        }else if (TextUtils.isEmpty(trim)){
          Utils.showToast(mContext.getString(R.string.content_is_empty));
        }else {
          Utils.showToast(mContext.getString(R.string.content_must_greater_than_10));
        }
        break;
      case R.id.popup_out:
        AddCommentWindow.this.dismiss();
        break;
    }
  }
}
